package com.example.warehousems.service;

import com.example.warehousems.component.UserInfo;
import com.example.warehousems.config.Constants;
import com.example.warehousems.dao.*;
import com.example.warehousems.dao.model.Cargo;
import com.example.warehousems.dao.model.JobTicket;
import com.example.warehousems.dao.model.OutList;
import com.example.warehousems.event.publisher.CargoInPublisher;
import com.example.warehousems.event.publisher.JobTicketPublisher;
import com.example.warehousems.vo.CargoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class JobTicketService {
    @Autowired
    private JobTicketPublisher jobTicketPublisher;
    @Autowired
    private CargoInPublisher cargoInPublisher;
    @Autowired
    private JobTicketRepository jobTicketRepository;
    @Autowired
    private OutListRepository outListRepository;
    @Autowired
    private StorageRepository storageRepository;
    @Autowired
    private CargoRepository cargoRepository;
    @Autowired
    private UserRepository userRepository;


    @Transactional
    public Constants.COMMONSTATUS confirm(Integer jobTicketId) {
        JobTicket jobTicket = jobTicketRepository.findById(jobTicketId).get();
        // 只有待确认的工单才能确认
        if (jobTicket.getStatus() != Constants.JOBTICKETSTATUS.TO_CONFIRM)
            return Constants.COMMONSTATUS.FAILURE;

        jobTicket.setStatus(Constants.JOBTICKETSTATUS.DONE); // 3-入库完成，正常存储

        for (Cargo cargo : jobTicket.getCargoList()) {
            cargo.setStatus(1); // 货物状态变为正常存储
            var storage = storageRepository.findByCargoId(cargo.getId());
            storage.setStatus(1); //表示被占用，正常存储

            cargoRepository.save(cargo);
            storageRepository.save(storage);
        }
        jobTicketRepository.save(jobTicket);

        jobTicketPublisher.publish(jobTicket);
        return Constants.COMMONSTATUS.SUCCESS;
    }

    @Transactional
    public Constants.COMMONSTATUS payment(Integer jobTicketId) {
        JobTicket jobTicket = jobTicketRepository.findById(jobTicketId).get();
        // 只有待支付的工单才能被支付
        if (jobTicket.getStatus() != Constants.JOBTICKETSTATUS.TO_PAY)
            return Constants.COMMONSTATUS.FAILURE;

        jobTicket.setStatus(Constants.JOBTICKETSTATUS.TO_CONFIRM); // 2-支付完成，正在入库

        for (Cargo cargo : jobTicket.getCargoList()) {
            cargoInPublisher.publish(cargo);
        }
        jobTicketRepository.save(jobTicket);

        jobTicketPublisher.publish(jobTicket);
        return Constants.COMMONSTATUS.SUCCESS;
    }

    @Transactional
    public Constants.COMMONSTATUS cancelPayment(Integer jobTicketId) {
        JobTicket jobTicket = jobTicketRepository.findById(jobTicketId).get();
        // 只有待支付的工单才能被取消支付
        if (jobTicket.getStatus() != Constants.JOBTICKETSTATUS.TO_PAY)
            return Constants.COMMONSTATUS.FAILURE;

        jobTicket.setStatus(Constants.JOBTICKETSTATUS.FAIL); // -1 工单报废
        for (Cargo cargo : jobTicket.getCargoList()) {
            OutList outList = cargo.getOutList();
            if (outList == null) {
                System.out.println("OutList为空");
                continue;
            }
            if (!outList.getIs_delete()) {
                System.out.println("更新OutList");
                outList.setIs_delete(true);
                outListRepository.save(outList);
            }
        }
        jobTicketRepository.save(jobTicket);
        jobTicketPublisher.publish(jobTicket);
        return Constants.COMMONSTATUS.SUCCESS;
    }

    @Transactional
    public Constants.COMMONSTATUS addSuggestion(Integer jobTicketId, String adminSug, Boolean isPassed) {
        JobTicket jobTicket = jobTicketRepository.findById(jobTicketId).get();
        // 只有待审核的工单才能被审核
        if (jobTicket.getStatus() != Constants.JOBTICKETSTATUS.TO_CHECK)
            return Constants.COMMONSTATUS.FAILURE;

        jobTicket.setAdminSug(adminSug);
        if (isPassed) {
            jobTicket.setStatus(Constants.JOBTICKETSTATUS.TO_PAY); // 1-审核完成，待支付
        }else {
            jobTicket.setStatus(Constants.JOBTICKETSTATUS.FAIL); // 管理员不通过，工单报废
            for (Cargo cargo : jobTicket.getCargoList()) {
                OutList outList = cargo.getOutList();
                if (outList == null) {
                    System.out.println("OutList为空");
                    continue;
                }
                if (!outList.getIs_delete()) {
                    System.out.println("更新OutList");
                    outList.setIs_delete(true);
                    outListRepository.save(outList);
                }
            }
        }
        jobTicketRepository.save(jobTicket);
        jobTicketPublisher.publish(jobTicket);
        return Constants.COMMONSTATUS.SUCCESS;
    }

    public Page<JobTicket> getJobTicket(int userId, Pageable pageable) {
        Page<JobTicket> jobTickets = null;
        if (UserInfo.get("role").equals("admin")){
            jobTickets = jobTicketRepository.findAllPageByAdmin_IdOrderByCreateTimeDesc(userRepository.findFirstByRole(0).getId(), pageable);
        }
        else{
            var user = userRepository.findUserById(userId);
            jobTickets = jobTicketRepository.findAllPageByProposer(user, pageable);
        }

        for (JobTicket jobTicket : jobTickets) {
            jobTicket.setProposer(null);
            jobTicket.setAdmin(null);
        }
        return jobTickets;
    }

    // 管理员获取自己需要审核的工单，用户获取自己的工单
    public List<JobTicket> getJobTicket(Integer userId) {
        List<JobTicket> jobTickets = null;
        if (UserInfo.get("role").equals("admin")){
            jobTickets = jobTicketRepository.findAllByAdmin_IdOrderByCreateTimeDesc(userRepository.findFirstByRole(0).getId());
        }
        else{
            var user = userRepository.findUserById(userId);
            jobTickets = jobTicketRepository.findAllByProposer(user);
        }

        for (JobTicket jobTicket : jobTickets) {
            jobTicket.setProposer(null);
            jobTicket.setAdmin(null);
        }
        return jobTickets;
    }

    public Integer generateJobTicket(JobTicket jobTicket, List<Cargo> cargos) {
        jobTicket.setStatus(Constants.JOBTICKETSTATUS.TO_CHECK);
        jobTicket = jobTicketRepository.save(jobTicket);

        float price = 0.0f;
        for (Cargo cargo : cargos) {
            float cost = 0.0f;
            cost = (cargo.getHeight() * cargo.getWidth() * cargo.getHeight()) * 2;
            if (cargo.getWeight() * 3 > cost)
                cost = cargo.getWeight() * 3;
            price += cost;

            cargo.setJobTicket(jobTicket);
            cargoRepository.save(cargo);
        }
        jobTicket.setPrice(price);

        jobTicketPublisher.publish(jobTicket);
        return jobTicket.getId();
    }

    public float calculatePrice(List<CargoVO> cargoVOs) {
        float price = 0.0f;
        for (CargoVO cargoVO : cargoVOs) {
            float cost = 0.0f;
            cost = (cargoVO.getHeight() * cargoVO.getWidth() * cargoVO.getHeight()) * 2;
            if (cargoVO.getWeight() * 3 > cost)
                cost = cargoVO.getWeight() * 3;
            price += cost;
        }
        return price;
    }

    public JobTicket getJobTicketById(Integer jobTicketId) {
        JobTicket jobTicket = null;
        if(UserInfo.get("role").equals("admin")){
            jobTicket = jobTicketRepository.findJobTicketById(jobTicketId);
        }
        else {
            Integer userId = Integer.valueOf(UserInfo.get("id"));
            jobTicket = jobTicketRepository.findJobTicketByIdAndProposerOrderByCreateTimeDesc(jobTicketId, userRepository.findUserById(userId));
        }

        if(jobTicket == null)
            return null;
        jobTicket.setProposer(null);
        jobTicket.setAdmin(null);
        return jobTicket;
    }
}
